package com.example.chatservice.rabbitmq.consumer;

import com.example.chatservice.mapper.ChatMessageMapper;
import com.example.chatservice.webSocket.ChannelContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.example.entity.constants.Constants;
import org.example.entity.dto.MessageSendDto;
import org.example.entity.po.ChatMessage;
import org.example.entity.query.ChatMessageQuery;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Description
 * @Author susu
 * @Date 2024/10/7
 */
@Component
@Slf4j
public class ChatConsumer {

    @Resource
    private ChatMessageMapper<ChatMessage, ChatMessageQuery> chatMessageMapper;
    @Resource
    private ChannelContextUtils channelContextUtils;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = Constants.CHAT_QUEUE),
            exchange = @Exchange(name = Constants.EXCHANGE_CHAT_TOPIC_NAME,type = ExchangeTypes.TOPIC),
            key = {Constants.CHAT_QUEUE_ROUTING_KEY}
    ))
    public void listenChatQueue(Object msg){
        if (msg instanceof ChatMessage){
            ChatMessage ch = (ChatMessage) msg;
            chatMessageMapper.insert(ch);
        }
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = Constants.QUEUE_CHAT_NAME),
            exchange = @Exchange(name = Constants.EXCHANGE_CHAT_TOPIC_NAME,type = ExchangeTypes.TOPIC),
            key = {Constants.ROUTING_KEY_CHAT}
    ))
    public void listenSendChatQueue(Object msg){
        if (msg instanceof MessageSendDto){
            MessageSendDto dto = (MessageSendDto) msg;
            channelContextUtils.sendMessage(dto);
        }
        if (msg instanceof String[]){
            String[] MsgString = (String[]) msg;
            channelContextUtils.addUser2Group(MsgString[0],MsgString[1]);
        }
    }
}
